#include <vector>
using namespace std;

struct TreeNode
{
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    TreeNode* _build(vector<int>& preorder, vector<int>& inorder,
                    int& prei, int inbegin, int inend)
    {
        if(inbegin > inend)
            return nullptr;

        TreeNode* root = new TreeNode(preorder[prei]);
        int ini = inbegin;
        while(ini <= inend)
        {
            if(preorder[prei] == inorder[ini])
                break;
            ini++;
        }
        prei++;
        root->left = _build(preorder, inorder, prei, inbegin, ini-1);
        root->right = _build(preorder, inorder, prei, ini+1, inend);
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
    {
        int i = 0;
        return _build(preorder, inorder, i, 0, inorder.size()-1);
    }
};
